using System;
using System.Collections.Generic;
using System.Text;

using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Navigation;

using TweakSP.Web.ContentService;

namespace TweakSP.Deployment
{
    public abstract class DeploymentUtilities
    {
        /// <summary>
        /// Adds a new navigation node to the END of the TopNavigationBar and QuickLaunch
        /// </summary>
        /// <param name="webUrl">Fully Quallifed URL of the Web</param>
        /// <param name="navTitle"></param>
        /// <param name="navUrl"></param>
        public static void AddAdminNavigationNode(string webUrl, string navTitle, string navUrl)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // Even though /_admin/* pages are internal, they must be added as external links
                        SPNavigationNode node = new SPNavigationNode(navTitle, navUrl, true);

                        web.Navigation.TopNavigationBar.AddAsLast(node);

                        SPNavigationNode caNode = web.Navigation.QuickLaunch[0];    // Grab the Central Admin navigation node
                        caNode.Children.AddAsLast(node);                            // Add the same Navigation node to the QuickLaunch

                        web.Update();

                    }
                }

            });
        }
        

        /// <summary>
        /// Searches the TopNavigationBar and QuickLaunch, removing nodes that match the provided URL
        /// </summary>
        /// <param name="webUrl">Fully Quallifed URL of the Web</param>
        /// <param name="navUrl"></param>
        public static void RemoveAdminNavigationNode(string webUrl, string navUrl)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        for (int x = web.Navigation.TopNavigationBar.Count; x > 0; x--)
                        {
                            SPNavigationNode node = web.Navigation.TopNavigationBar[x-1];
                            if (node.Url == navUrl)
                            {
                                node.Delete();
                            }
                        }

                        for (int x = web.Navigation.QuickLaunch[0].Children.Count; x > 0; x--)
                        {
                            SPNavigationNode node = web.Navigation.QuickLaunch[0].Children[x-1];
                            if (node.Url == navUrl)
                            {
                                node.Delete();
                            }
                        }

                        web.Update();
                    }
                }

            });
        }


        /// <summary>
        /// Rebuilds and deploys resources.  This is the copyappbincontent STSADM command
        /// http://msdn2.microsoft.com/en-us/library/bb862651.aspx
        /// http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebservice.applyapplicationcontenttolocalserver.aspx
        /// </summary>
        public static void CopyAppBinContent()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPServiceInstance localContent = SPWebServiceInstance.LocalContent;
                if ((localContent != null) && (localContent.Status == SPObjectStatus.Online))
                {
                    SPWebService.ContentService.ApplyApplicationContentToLocalServer();
                }
                localContent = SPWebServiceInstance.LocalAdministration;
                if ((localContent != null) && (localContent.Status == SPObjectStatus.Online))
                {
                    SPWebService.AdministrationService.ApplyApplicationContentToLocalServer();
                }




            });
        }

        public static string GetCentralAdminWebUrl()
        {
            string caUrl = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                caUrl = SPAdministrationWebApplication.Local.AlternateUrls[0].IncomingUrl;
            });

            return caUrl;
        }

        public static void AddFeatureToWeb(string webUrl, Guid featureId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.Features.Add(featureId);
                    }
                }
            });
        }

        public static void AddFeatureToWebApplication(string webUrl, Guid featureId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(webUrl));

                webApp.Features.Add(featureId);

            });
        }

        public static void RemoveFeatureFromWeb(string webUrl, Guid featureId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (web.Features[featureId] != null)    // If the feature is activated
                        {
                            web.Features.Remove(featureId, true);
                        }
                    }
                }
            });
        }

        public static void RemoveFeatureToWebApplication(string webUrl, Guid featureId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(webUrl));

                webApp.Features.Remove(featureId);

            });
        }

        public static void DeleteTimerJob(string webUrl, string jobName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {

                    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                    {
                        if (job.Name == jobName && job.WebApplication.Name == site.WebApplication.Name)
                        {
                            job.Delete();
                        }
                    }
                }
            });
        }

        public static void DeleteTimerJob(SPWebApplication webApp, string jobName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                foreach (SPJobDefinition job in webApp.JobDefinitions)
                {
                    if (job.Name == jobName && job.WebApplication.Name == webApp.Name)
                    {
                        job.Delete();
                    }
                }
            });
        }


        public static void InstallContentService()
        {
            /* Add the ContentService administration object to the database. */
            TweakSP_ContentService contentService = TweakSP_ContentService.Local;

            if (contentService == null)
            {
                contentService = new TweakSP_ContentService(SPFarm.Local);
                contentService.Update();
            }
        }
    }
}
